<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="theme-color" content="#000000"/>
    <meta name="description" content="测试control同时接受附件和json"/>
    <title>测试control同时接受附件和json</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
<noscript>运行此App需要打开JavaScript功能</noscript>
<div id="root">
    <form id="data-form" enctype="multipart/form-data" method="post">
        <div>
            <label for="user"></label>
            <textarea id="user" name="user" cols="40" rows="5">{"firstName":"free","lastName":"water","age":18,"address":"chengdu"}</textarea>
        </div>
        <div>
            <label for="file"></label>
            <input id="file" name="file" type="file"/>
        </div>
        <div>
            <button type="reset">重置</button>
            <button type="submit">提交</button>
        </div>
    </form>
    <script>
        const form = document.getElementById("data-form");
        form.onsubmit = (event) => {
            event.preventDefault();
            const user = document.getElementById("user").value;
            // 把json字符串包装成“文件”
            const formData = new FormData(form);
            const userBlob = new Blob([user], {type: "application/json"});
            formData.set("user", userBlob);
            //
            axios.post("/user/addUser", formData,
                {
                    withCredentials:true, // 携带cookie
                    //auth:{username:"user", password:"123456"}, // Base auth
                })
                .then(function (response) {
                    console.log(response);
                    alert("提交成功: " + JSON.stringify(response.data || null));
                })
                .catch(function (error) {
                    console.log(error);
                    alert("提交失败")
                });
        }
    </script>
</div>
</body>
</html>